package com.crp.redis.dao;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Repository
public class RedisDao {

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	private HashOperations<String, String, Object> hashOperations;

	/**
	 * 缓存指定的数据
	 * hset
	 * 
	 * @param key 缓存区KEY
	 * @param field 缓存区filed
	 * @param value
	 *            Object to Json
	 */
	public void setJsonStrForHash(String key, String field, Object value) {
		String jsonStr = (value instanceof String) ? (String) value : JSONObject.toJSONString(value);
		this.getHashOperations().put(key, field, jsonStr);
	}

	/**
	 * 获取指定的数据
	 * hget
	 * 
	 * @param key 缓存区KEY
	 * @param field 缓存区filed
	 * @param clazz Json to Object
	 * @return
	 */
	public <T> T getObjectFromHash(String key, String field, Class<T> clazz) {
		String jsonStr = (String) this.getHashOperations().get(key, field);
		return (clazz == String.class) ? (T) jsonStr : JSONObject.parseObject(jsonStr, clazz);
	}

	/**
	 * 获取key下的所有hash值
	 * hgetall
	 * 
	 * @param key
	 * @return
	 */
	public Map<String, Object> getEntriesByHashKey(String key) {
		Map<String, Object> entries = this.getHashOperations().entries(key);
		return entries;
	}

	/**
	 * 是否存在
	 * 
	 * @param key
	 * @param field
	 * @return
	 */
	public boolean exixts(String key, String field) {
		return this.getHashOperations().hasKey(key, field);
	}

	/**
	 * 删除指定的数据
	 * hdel
	 * 
	 * @param key
	 * @param hashKeys
	 */
	public void removeObjectsBykey(String key, Object... hashKeys) {
		getHashOperations().delete(key, hashKeys);
	}

	/**
	 * redisTemplate的代理方法
	 * 
	 * @return
	 */
	private HashOperations<String, String, Object> getHashOperations() {
		if (null == this.hashOperations) {
			this.hashOperations = redisTemplate.opsForHash();
		}
		
		return this.hashOperations;
	}

	/**
	 * 设置有失效时间的数据
	 * @param key
	 * @param field
	 * @param value
	 * @param timeout
	 */
	public void setExpireJsonStrForHash(String key, String field, Object value, long timeout) {
		this.setJsonStrForHash(key, field, value);
		this.redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
	}

	/**
	 * 根据KEY获取所有的filed
	 * @param key
	 * @return
     */
	public Set<String> queryFieldsByHashKey(String key) {
		return this.getHashOperations().keys(key);
	}
}
